package com.vxdata.utils.modules.weixin.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;

@Slf4j
public class WXBizMsgCrypt {

    /**
     * aes解密
     * @param sessionKey 登录凭证校验 的 会话秘钥
     * @param encryptedData
     * @param ivStr
     * @return
     */
    public static String decrypt(String sessionKey, String encryptedData, String ivStr) {
        // Base64解码后 转为 字节数组
        byte[] bizData = java.util.Base64.getDecoder().decode(encryptedData);
        byte[] keyByte = java.util.Base64.getDecoder().decode(sessionKey);
        byte[] ivByte = java.util.Base64.getDecoder().decode(ivStr);
        try {
            // Cipher类为加密和解密提供密码功能
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            // 初始化
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, params);
            byte[] original = cipher.doFinal(bizData);
            // 去除补位字符
            byte[] result = PKCS7Encoder.decode(original);
            return new String(result, Charsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("aes解密失败");
        }
    }
}
